<template>
    <base-breadcrumb :title="title" :breadcrumb="!isAudit">
        <!-- 期中结算报送审批编辑 -->
        <a-form-model
            ref="ruleForm"
            :model="form"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            :rules="editModel != 0 ? rules : {}"
        >
            <a-spin :spinning="loading">
                <!-- 表格 -->
                <a-card :bordered="false">
                    <title-name title="基本信息"></title-name>
                    <custom-form
                        :formList="formList"
                        :form="form"
                        :isEmit="false"
                        :editModel="editModel == 0 ? '' : ''"
                        @getProjectInfo="getProjectInfo"
                    >
                        <template v-slot:table>
                            <a-form-model-item label=" " :colon="false">
                                <!-- 表格 -->
                                <s-table
                                    class="mb20"
                                    bordered
                                    ref="table"
                                    tableLayout="fixed"
                                    size="default"
                                    rowKey="id"
                                    :columns="columns"
                                    :data="loadData"
                                    :alert="true"
                                    show-size-changer
                                    show-quick-jumper
                                    :showPagination="false"
                                >
                                    <template
                                        v-for="col in ['tax', 'includeTax', 'excludingTax', 'remark']"
                                        :slot="col"
                                        slot-scope="text, record, index"
                                    >
                                        <div :key="col" class="form-item">
                                            <template>
                                                <template v-if="editModel != 0">
                                                    <BaseInput
                                                        v-if="col === 'remark'"
                                                        :class="col === 'remark' ? 'remark' : ''"
                                                        :disabled="editModel == 0"
                                                        v-model="record[col]"
                                                    >
                                                    </BaseInput>
                                                    <span v-else-if="col === 'includeTax'"
                                                        >{{ text }}
                                                    </span>

                                                    <BaseInputNumber
                                                        v-else
                                                        v-model="record[col]"
                                                        :disabled="editModel == 0"
                                                        :precision="2"
                                                        @change="change(index)"
                                                    >
                                                    </BaseInputNumber>
                                                </template>
                                                <template v-else> {{ text }}</template>
                                            </template>
                                        </div></template
                                    ></s-table
                                >
                            </a-form-model-item>
                        </template>

                        <!-- 附件上传 -->
                        <template #filesInfo>
                            <template v-if="editModel != 0">
                                <l-table businessCode="BM27" :uploadArrys.sync="form.filesInfo"></l-table>
                                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
                            </template>
                            <file-link v-else :fileList="form.filesInfo" style="margin-top: -3px"></file-link>
                        </template>
                    </custom-form>
                </a-card>

                <!-- 页脚操作栏 -->
                <div class="btn_box page-btn-right-top" v-if="editModel != 0 && !isConsultation">
<!--                    <a-button-->
<!--                        class="button_right"-->
<!--                        v-if="form.status == 'REJECTED'"-->
<!--                        type="primary"-->
<!--                        :disabled="isName"-->
<!--                        :loading="loading.REJECTED"-->
<!--                        @click="handleSubmit('REJECTED')"-->
<!--                        >保存</a-button-->
<!--                    >-->
<!--                    <a-button-->
<!--                        v-else-->
<!--                        class="button_right"-->
<!--                        type="primary"-->
<!--                        :loading="loading.DRAFT"-->
<!--                        :disabled="isName"-->
<!--                        @click="handleSubmit('DRAFT')"-->
<!--                        >保存草稿</a-button-->
<!--                    >-->
                    <a-button
                        class="button_right"
                        type="primary"
                        :loading="loading.SUBMITTED"
                        @click="handleSubmit('SUBMITTED')"
                        :disabled="isName"
                        >提交</a-button
                    >
                    <a-button type="primary" @click="handleActiveClose">关闭</a-button>
                </div>
                <div class="btn_box page-btn-right-top" v-else-if="!isConsultation">
                    <a-button type="primary" @click="handleActiveClose">关闭</a-button>
                </div>
            </a-spin>
        </a-form-model>
         <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>

<script>
import {
    getSubmissionNameList,
    getSubmission,
    updateApprovalTerm,
    getApprovalTerm,
    addApprovalTerm
} from '@/api/businessAffairs/revenueAndCost'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import moment from 'moment'
import { position } from './model.js'
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import _ from 'lodash'
const columns = [
    {
        title: '项目/金额',
        dataIndex: 'projectType'
    },
    {
        title: '1.不含增值税(万元)',
        dataIndex: 'excludingTax',
        scopedSlots: { customRender: 'excludingTax' }
    },
    {
        title: '2.增值税(万元)',
        dataIndex: 'tax',
        scopedSlots: { customRender: 'tax' }
    },
    {
        title: '含增值税(万元)(1+2)',
        dataIndex: 'includeTax',
        scopedSlots: { customRender: 'includeTax' }
    },
    {
        title: '备注',
        dataIndex: 'remark',
        scopedSlots: { customRender: 'remark' }
    }
]
export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    components: {
        SelectPersonModal
    },
    data() {
        this.columns = columns
        return {
            loading: false, // 加载控件
            visible: false, //人员选择控件
            editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
            form: {
                projectId:null,
                nameList: [],
                sendName: '',
                structureType: '',
                areaOfStructure: '',
                profit: 0,
                profitMargin: 0,
                contractInfo: '',
                projectTotalDTOS: [
                    {
                        tax: null,
                        excludingTax: null,
                        includeTax: null,
                        remark: null,
                        projectType: '报审值'
                    },
                    {
                        tax: null,
                        excludingTax: null,
                        includeTax: null,
                        remark: null,
                        projectType: '实际成本'
                    },
                    {
                        tax: null,
                        excludingTax: null,
                        includeTax: null,
                        remark: null,
                        projectType: '审定金额'
                    }
                ]
            }, // 表单
            id: '',
            loadData: () => {
                if (this.form.projectTotalDTOS.length > 0) {
                    return new Promise((resolve, reject) => {
                        resolve({
                            data: this.form.projectTotalDTOS
                        })
                    })
                }
            },
            loadingBtn: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            rules: {
                proportion: [{ required: true, message: '请输入' }],
                // midId: [{ required: true, message: '请输入' }],
                partName: [{ required: true, message: '请输入' }],
                contractInfo: [{ required: true, message: '请输入' }]
            }, // 校验规则
            init: false, // 初始化控件
            isName: false,
            nameList: [],
            disabledDateList: [],
            titles: ['期中结算定案审批 查看', '期中结算定案审批 编辑', '期中结算定案审批 新增'],
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null,
            area: 0
        }
    },
    props: {
        // 是否作为审批详情
        isAudit: {
            type: Boolean,
            default: false
        },
        // 是否作为意见征询
        isConsultation: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.editModel = 0
                    })
                }
            }
        },
        'form.midId'() {
            // this.getSubmissionDetails(this.form.midId)
        }
    },
    async mounted() {
        // 不为添加时请求详情
        if (this.editModel != 2) {
            this.loading = true
            getApprovalTerm({ id: this.id })
                .then((res) => {
                    this.loading = false
                    if(!res[1].data.projectTotalDTOS || res[1].data.projectTotalDTOS.length === 0) {
                        res[1].data.projectTotalDTOS = [
                            {
                                tax: null,
                                excludingTax: null,
                                includeTax: null,
                                remark: null,
                                projectType: '报审值'
                            },
                            {
                                tax: null,
                                excludingTax: null,
                                includeTax: null,
                                remark: null,
                                projectType: '实际成本'
                            },
                            {
                                tax: null,
                                excludingTax: null,
                                includeTax: null,
                                remark: null,
                                projectType: '审定金额'
                            }
                        ]
                    }
                    this.form = { ...this.form, ...res[1].data }
                    // this.getProjectInfo()
                    console.log(this.form)

                    this.$nextTick(() => {
                        this.init = true
                        this.form.payment = this.form.payment ? 1 : 0

                        this.$refs.table.refresh(true)
                    })
                })
                .catch(() => {
                    this.loading = false
                })
        } else {
            this.form.projectId = this.$userInfo().currentPost.projectId;
            this.$nextTick(() => {
                this.init = true
            })
        }
      //获取通过获取流程配置值
      //  this.processConfig = await this.$getConfigFn('approval_of_term_settlement')
    },
    computed: {
        formList() {
            return [
                {
                    label: '所属单位',
                    type: 'orgTree',
                    keyName: 'projectId',
                    rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                    span: 16,
                    isAutoSelectFirst: false,
                    isQueryProjecDetail: true,
                    isNeedAuth:true ,
                    checkStrictly: true,
                    disabled: true,
                    viewName: "viewName",
                },
                // {
                //     type: SelectSubCompany,
                //     keyName: 'branchComId',
                //     label: '所属分公司',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2
                //     }
                // },
                // {
                //     type: SelectProject,
                //     keyName: 'projectId',
                //     label: '所属项目',
                //     placeholder: ' ',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2,
                //         keyValue: 'branchComId',
                //         isClear: this.editModel == 2,
                //         isEdit: this.editModel != 2,
                //         form: this.form
                //     },
                //     selectChange: async (e) => {
                //         const [err, res] = await getSubmissionNameList({
                //             projectId: e.code,
                //             branchComId: this.form.branchComId,

                //             midId: this.form.midId
                //         })
                //         if (!err) {
                //             res.data.forEach((i) => {
                //                 i.label = i.name
                //                 i.value = i.id
                //             })
                //             this.form.nameList = res.data
                //             console.log(this.form.nameList)
                //         }
                //     }
                // },
                {
                    keyName: 'midId',
                    type: 'a-input',
                    disabled: true,
                    label: '名称'
                },
                {
                    label: '结算部位',
                    keyName: 'partName',
                    disabled: this.editModel == 0,
                    type: 'a-input',
                      placeholder: '请输入'
                },
                {
                    keyName: 'sendName',
                    type: 'BaseInput',
                    disabled: true,
                    label: '发包人全称'
                },
                {
                    keyName: 'structureType',
                    type: 'BaseInput',
                    disabled: true,
                    label: '结构类型'
                },
                {
                    keyName: 'areaOfStructure',
                    type: 'BaseInput',
                    disabled: true,
                    label: '建筑面积m²'
                },
                {
                    keyName: 'overRideContractFee',
                    type: 'a-radio-group',
                    disabled: this.editModel == 0,
                    label: '是否突破合同进行结算',
                    data: [
                        {
                            label: '否',
                            value: false
                        },
                        {
                            label: '是',
                            value: true
                        }
                    ]
                },
                {
                    keyName: 'payment',
                    type: 'a-radio-group',
                    disabled: this.editModel == 0,
                    label: '是否提高付款比例',
                    data: [
                        {
                            label: '否',
                            value: 0
                        },
                        {
                            label: '是',
                            value: 1
                        }
                    ]
                },
                {
                    keyName: 'proportion',
                    type: 'BaseInputNumber',
                    hidden: this.form.payment != 1,
                    precision: 2,
                    disabled: this.editModel == 0,
                    label: '提高后付款比例(%)'
                },
                {
                    keyName: 'contractInfo',
                    type: 'BaseTextarea',
                    disabled: this.editModel == 0,
                    label: '合同内期中结算相关说明',
                    span: 24
                },
                {
                    slot: true,
                    customItemSlot: true,
                    keyName: 'table',
                    span: 24
                },
                {
                    keyName: 'profit',
                    type: 'BaseInputNumber',
                    precision: 2,
                    disabled: true,
                    label: '利润额(含税)(万元)'
                },
                {
                    keyName: 'profitMargin',
                    type: 'BaseInputNumber',
                    precision: 2,
                    disabled: true,
                    label: '利润率%'
                },
                {
                    slot: true,
                    keyName: 'filesInfo',
                    label: '附件上传',
                    span: 24
                }
            ]
        }
    },
    methods: {
        getProjectInfo(e) {
            this.form.areaOfStructure =  e.contractTotalArea * 100 * 100
            this.form.sendName = e.constructionName
            this.form.structureType = e.structureTypeName
        },
        //获取项目详情
        // async getProjectInfo() {
        //     const [err, res] = await getSubmissionNameList({
        //         projectId: this.form.projectId,
        //         branchComId: this.form.branchComId,
        //         midId: this.form.midId
        //     })
        //     if (!err) {
        //         res.data.forEach((i) => {
        //             i.label = i.name
        //             i.value = i.id
        //         })
        //         this.form.nameList = res.data
        //     }
        // },
        getSubmissionDetails(e) {
            if (!e) return
            this.loading = true

            getSubmission({ id: e }).then((res) => {
                this.loading = false
                console.log()
                // this.form.partId = res[1].data.partId
                // this.form.sendName = res[1].data.sendName
                // this.form.structureType = res[1].data.structureType
                // this.form.areaOfStructure = res[1].data.areaOfStructure
                this.form.contractInfo = res[1].data.contractInfo

                this.form.overRideContractFee = res[1].data.overRideContractFee ? 1 : 0
                this.form.projectTotalDTOS[0].excludingTax = res[1].data.midInfoDetail[0].notContainTaxFee
                this.form.projectTotalDTOS[0].tax = res[1].data.midInfoDetail[0].taxFee
                this.form.projectTotalDTOS[0].includeTax = res[1].data.midInfoDetail[0].containTaxFee
                this.form.projectTotalDTOS[1].excludingTax = res[1].data.midInfoDetail[2].notContainTaxFee
                this.form.projectTotalDTOS[1].tax = res[1].data.midInfoDetail[2].taxFee
                this.form.projectTotalDTOS[1].includeTax = res[1].data.midInfoDetail[2].containTaxFee
                this.calculateProfit()
                console.log(this.form)
            })
        },
        /**
         * 输入框事件
         */
        change(index) {
            this.$nextTick(() => {
                if (
                    this.form.projectTotalDTOS[index].tax != null &&
                    this.form.projectTotalDTOS[index].excludingTax != null
                ) {
                    this.form.projectTotalDTOS[index].includeTax =
                        this.form.projectTotalDTOS[index].tax + this.form.projectTotalDTOS[index].excludingTax
                } else if (
                    this.form.projectTotalDTOS[index].tax == null &&
                    this.form.projectTotalDTOS[index].excludingTax == null
                ) {
                    this.form.projectTotalDTOS[index].includeTax = 0
                }
                this.calculateProfit()
            })
        },
        calculateProfit() {
            this.form.profit = this.form.projectTotalDTOS[2].includeTax - this.form.projectTotalDTOS[1].includeTax
            if(this.form.projectTotalDTOS[2].includeTax) {
                this.form.profitMargin = (this.form.profit / this.form.projectTotalDTOS[2].includeTax) * 100
            } else {
                this.form.profitMargin = ''
            }

            // this.$refs.table.refresh(true)
        },
        validateTable(list) {
            let flag = false

            list.forEach((item) => {
                if (item.excludingTax == null || item.tax == null) {
                    flag = true
                }
            })
            if (flag) {
                this.$message.warning('请完善表格后提交')
            }
            return flag
        },
        validateForm() {
            let flag = false
            this.$refs.ruleForm.validate((e) => {
                if (e) {
                    flag = true
                }else {
                  this.$message.warning('请填写完所有必填项信息')
                }
            })
            return flag
        },
        /**
         * 提交表单
         */
        async handleSubmit(status) {
             this.setProcessConfig = null;
            if (status == 'SUBMITTED') {
                // 校验表单
                if (!this.validateForm() || this.validateTable(this.form.projectTotalDTOS)) {
                    return
                }
            }

            this.loading = true
            this.loadingBtn[status] = true
            this.form.status = status
            let form = this.$clone(this.form)
            form.postCode = this.$userInfo().currentPost.postCode
            form.midId = null;
            // form.partName = position.filter((i) => i.value == form.partId)[0]?.label
            if (form.payment == 0) {
                form.payment = false
            } else if (form.payment == 1) {
                form.payment = true
            }
            this.submitApprovalConfirm(6, async (flag)=>{
              if(!flag) {
                this.loading = false
                this.loadingBtn[status] = false
                return
              }
              let api = [updateApprovalTerm, addApprovalTerm][this.editModel - 1] // 根据操作切换url地址
            const [err, res] = await api(form)
            this.loading = false
            this.loadingBtn[status] = false
            if (!err) {
                this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
                //  if(status =='SUBMITTED') {
                // //提交时，返回id
                //     this.businessId = res.data.id || this.id;
                //     this.setProcessConfig = this.processConfig;
                //     return
                // }else{
                  this.$multiTab.close()
                 // }
            } else {
                this.$message.warning(err.data.message)
            }
            })
        }
    }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
    .ant-input:not([disabled]),
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number:not([disabled]),
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
    .remark {
        .ant-input {
            border-color: inherit;
            background-color: initial;
        }
    }
}
</style>
